// pages/game/skillCertification/skillCertification.js
const app = getApp()

//微信小程序新录音接口，录出来的是aac或者mp3，这里要录成mp3
const mp3Recorder = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const mp3RecoderOptions = {
  duration: 600000,
  sampleRate: 44100,
  numberOfChannels: 1,
  encodeBitRate: 64000,
  format: 'mp3',
  // frameSize: 50
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    api: '', //上传地址
    gameId: null, //游戏id
    gameName: null, //游戏名称
    zoneList: [], //区服列表
    introduce: '', //技能介绍
    chooseList: [], //复选框
    frontImage: '', //图片
    fileListfrontImage: [],
    showAction: false, //展示礼物弹出框
    giftList: [], //礼物列表 
    chooseGift: null, //选择的礼物
    showSkillLevel: false, //展示技能
    levelList: [], //等级列表
    chooseLevel: null, //选择的等级

    showAudio: false, //展示语言
    voice: null, //录音文件
  },
  // 录音
  startRecord() {
    let that = this
    //开始录音  
    that.setData({
      showAudio: true,
      voice: null, //录音文件
    })
    // wx.startRecord({
    //   success: function (e) {
    //     var voice = e.tempFilePath
    //     console.log(voice)
    //     that.setData({
    //       voice:voice
    //     })
    //   }
    // })
    mp3Recorder.start(mp3RecoderOptions);

  },
  // 停止录音
  stopRecord() {
    //结束录音  
    // wx.stopRecord();
    mp3Recorder.stop();
    this.setData({
      showAudio: false
    })
  },
  playRecord() {
    //播放声音文件  
    // wx.playVoice({
    //   filePath: this.data.voice
    // })
    innerAudioContext.src =  this.data.voice
    innerAudioContext.play()
  },
  //postInfo  提交审核
  postInfo() {
    let that = this
    // console.log(postObj)
    if (!!!this.data.gameId || !!!this.data.chooseLevel || !!!this.data.chooseGift || !!!this.data.frontImage || !!!this.data.introduce || this.data.chooseList.length <= 0 || !!!this.data.voice) {
      wx.showToast({
        title: '提交参数不全',
        icon: "none"
      })
    } else {
      var postObj = {
        gameId: this.data.gameId, //	是	int	游戏ID
        levelId: this.data.chooseLevel.levelId, //	是	int	游戏等级ID
        giftId: this.data.chooseGift.id, //	是	int	礼物ID
        userId: wx.getStorageSync('userId'), //	是	int	用户ID
        url: this.data.frontImage, //	是	string	图片地址
        introduce: this.data.introduce, //	是	string	技能介绍
        districtId: this.data.chooseList, //	是	int	游戏区服ID
        voice:this.data.voice,
      }
      var obj = {
        url: '/manage/client/info',
        method: 'POST',
        data: postObj
      }
      app.request.gameRequest(obj).then(res => {
        wx.showToast({
          title: '提交成功',
          icon: "success",
          success: () => {
            setTimeout(() => {
              wx.navigateBack({
                delta: -1,
              })
            }, 1500)
          }
        })
      }).catch(err => {})
    }
  },


  // 获取技能等级列表
  // /client/gamelevel/list
  // 传gameId
  // get请求
  gamelevel() {
    var getObj = {
      url: '/manage/client/gamelevel/list',
      method: 'GET',
      data: {
        gameId: this.data.gameId
      }
    }
    app.request.gameRequest(getObj).then(res => {
      // console.log('获取技能等级列表1', res)
      var levelList = res.data.data.list
      levelList.forEach((items, i) => {
        items.text = items.levelName
      })
      console.log('获取技能等级列表', levelList)
      this.setData({
        levelList: levelList
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },
  // 展示等级
  showSkillLevel() {
    this.setData({
      showSkillLevel: true
    })
  },
  // 关闭等级
  onCloseLevel() {
    this.setData({
      showSkillLevel: false
    })
  },
  // 确认等级
  onConfirmLevel(e) {
    var value = e.detail.value
    console.log('点击确定', value)

    this.setData({
      chooseLevel: value,
      showSkillLevel: false
    });

  },

  //获取礼物列表   /client/info/getGift
  getGift() {
    var postObj = {
      url: '/manage/client/info/getGift',
      method: 'GET'
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('获取礼物列表', res)
      var giftList = res.data.data
      giftList.forEach((items, i) => {
        items.text = items.giftName + ' / ' + items.needCoin + '幸运币'
      })
      this.setData({
        giftList: giftList
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },

  // 上传前校验
  beforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    callback(file.type === 'image');
  },
  // 删除 身份证 前面
  deleteReadfrontImage() {
    this.setData({
      fileListfrontImage: [],
      'frontImage': ''
    })
  },
  // 上传后校验    身份证 前面
  afterReadfrontImage(event) {
    let that = this
    const {
      file
    } = event.detail;
    console.log(file);
    console.log(this.data.fileListfrontImage);

    // url: that.data.api, // 仅为示例，非真实的接口地址
    // filePath: tempFilePath,
    // name: 'file',
    // formData: {
    //   file: tempFilePath
    // },


    wx.uploadFile({
      url: that.data.api, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {
        // user: 'test'
        file: file
      },
      success(res) {
        console.log('上传完成', res);
        var data = JSON.parse(res.data)
        console.log('data', data)
        var fileList = []
        fileList.push({
          url: data.data,
          name: data.data
        })
        that.setData({
          fileListfrontImage: fileList,
          'frontImage': data.data
        });
      },
    });

  },
  isImage(fileName) {
    if (typeof fileName !== 'string') return;
    let name = fileName.toLowerCase();
    return name.endsWith('.png') || name.endsWith('.jpeg') || name.endsWith('.jpg') || name.endsWith('.png') || name.endsWith('.bmp');
  },

  //查询游戏区服
  getZoneList() {
    var postObj = {
      url: '/manage/client/game/district/list',
      method: 'GET',
      data: {
        gameId: this.data.gameId
      }
    }
    app.request.gameRequest(postObj).then(res => {
      console.log('查询游戏区服', res)
      // console.log(res.data.data)
      this.setData({
        zoneList: res.data.data
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },

  // 点击确定
  onConfirm(e) {

    var value = e.detail.value
    console.log('点击确定', value)

    this.setData({
      chooseGift: value,
      showAction: false
    });

  },
  showAction() {
    this.setData({
      showAction: true
    });
  },
  onCloseAction() {
    this.setData({
      showAction: false
    });
  },

  onSelectAction(event) {
    console.log(event.detail);
  },

  // 监听复选框
  onChangebox(event) {
    this.setData({
      chooseList: event.detail,
    });
    console.log(this.data.chooseList)
  },
  //监听技能介绍
  onChangefield(event) {
    console.log(event.detail);
    this.setData({
      introduce: event.detail
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    var gameId = options.gameId
    var gameName = options.gameName
    this.setData({
      gameId: gameId,
      gameName: gameName,
    })

    this.getZoneList()
    this.getGift()
    this.gamelevel()
    var before = app.util.config().api
    var after = '/shortVideo/resource/upload'
    var api = before + after
    console.log(api)
    this.setData({
      api: api
    })


    //onLoad中为录音接口注册两个回调函数，主要是onStop，拿到录音mp3文件的文件名（不用在意文件后辍是.dat还是.mp3，后辍不决定音频格式）
    mp3Recorder.onStart(() => {
      console.log('mp3Recorder.onStart()...')
    })
    mp3Recorder.onStop((res) => {
      console.log('mp3Recorder.onStop() ' + res)
      const {
        tempFilePath
      } = res


      // console.log("that.data.voice",that.data.voice)

      // 上传音频
      wx.uploadFile({
        url: that.data.api, // 仅为示例，非真实的接口地址
        filePath: tempFilePath,
        name: 'file',
        formData: {
          file: tempFilePath
        },
        success(res) {
          console.log('上传完成', res);
          var data = JSON.parse(res.data)
          console.log('data', data)

          that.setData({
            voice: data.data
          })
        },
      });
    })



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})